package 线程;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;

public class _3死锁的代码 {
    public static byte[] a = new byte[0];
    public static byte[] b = new byte[0];
    static CountDownLatch count;

    public static void main(String[] args) {
        ThreadA threadA = new ThreadA("this a");
        ThreadB threadB = new ThreadB("this b");
        count = new CountDownLatch(2);
        count.countDown();
        threadA.start();
        count.countDown();
        threadB.start();
        System.out.println("start");
    }

    public static class ThreadA extends Thread {
        private String name;

        public ThreadA(String name) {
            super(name);
            this.name = name;
        }

        @SneakyThrows
        @Override
        public void run() {
            System.out.println(1);
            while (true) {
                synchronized (a) {
                    Thread.sleep(1);
                    synchronized (b) {
                        System.out.println(getName());
                    }
                }

            }
        }
    }

    public static class ThreadB extends Thread {
        private String name;

        public ThreadB(String name) {
            super(name);
            this.name = name;
        }

        @SneakyThrows
        @Override
        public void run() {
            System.out.println(2);
            while (true) {
                synchronized (b) {
                    Thread.sleep(1);
                    synchronized (a) {
                        System.out.println(getName());
                    }
                }
            }
        }
    }
}
